<template>
  <el-dialog :title="title" v-model="open" width="500px" append-to-body>
    <el-form ref="goodsCategoryRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="所属分类" prop="parentId">
        <el-tree-select
          v-model="form.parentId"
          :data="goodsCategoryOptions"
          :props="{ value: 'id', label: 'name', children: 'children' }"
          value-key="id"
          placeholder="请选择所属分类"
          check-strictly
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, toRefs, watch } from 'vue';

const emit = defineEmits(['cancelBox', 'submitForm']);

const props = defineProps({
  title: {
    type: String,
    default: '新增商品分类'
  },
  open: {
    type: Boolean,
    required: true
  },
  formInfo: {
    type: Object,
    default: () => ({})
  },
  goodsCategoryOptions: {
    type: Array,
    required: true
  },
  rules: {
    type: Object,
    required: true
  }
});

const form = ref({
  id: null,
  name: null,
  parentId: null,
  isDelete: null,
  createTime: null
});

const goodsCategoryRef = ref(null);

const { title, open, formInfo, goodsCategoryOptions, rules } = toRefs(props);

watch(formInfo, (newValue) => {
  Object.assign(form.value, newValue);
}, { deep: true });

const submitForm = () => {
  goodsCategoryRef.value.validate(valid => {
    if (valid) {
      emit('submitForm', form.value);
    }
  });
};

const cancel = () => {
  emit('cancelBox');
  resetForm();
};

const resetForm = () => {
  Object.assign(form.value, {
    id: null,
    name: null,
    parentId: null,
    isDelete: null,
    createTime: null
  });
};

defineExpose({
  submitForm,
  resetForm
});
</script>

<style scoped>
</style>